package com.epam.dynamiccl;

import java.io.File;
import java.io.IOException;

/**
 * Custom class loader which catches changes in the dynamic content "on the fly"
 * 
 * @author Iurii Miedviediev
 * @version 1.0 Build 27.07.2014
 */
public class DynamicClassLoader extends ClassLoader {

	public DynamicClassLoader(ClassLoader parent) {
		super(parent);
	}

	@Override
	public Class<?> loadClass(String name) throws ClassNotFoundException {

		// if given file belongs to dynamic content
		if (name.startsWith("com.epam.dynamiccl.dynamiccontent")) {

			// if file is out-dated
			if (Util.needsUpdate(name)) {
				try {
					Util.compile(name);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			// found necessary class file
			String classFilename = Util.buildPath(
					name.replace('.', File.separatorChar), "target/classes",
					".class");
			File classFile = new File(classFilename);

			// load class to JVM
			byte[] bytes = null;
			try {
				bytes = Util.loadClassData(classFile);
				Class<?> clas = defineClass(name, bytes, 0, bytes.length);
				resolveClass(clas);
				return clas;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return super.loadClass(name);
	}

}